package com.kylin.system.common.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.kylin.common.core.util.SpringUtils;
import com.kylin.common.redis.service.RedisService;
import com.kylin.system.common.enums.SystemRedisKeys;
import com.kylin.system.entity.SysDictData;

import javax.validation.Valid;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典工具类
 * 
 * @author wuhao
 */
public class DictUtils
{
    private DictUtils() {
        throw new IllegalStateException("Utility class");
    }
    /**
     * 设置字典缓存
     * 
     * @param key 参数键
     * @param dictDatas 字典数据列表
     */
    public static void setDictCache(String key, @Valid List<SysDictData> dictDatas)
    {
        SpringUtils.getBean(RedisService.class).setCacheObject(getCacheKey(key), dictDatas);
    }

    /**
     * 获取字典缓存
     * 
     * @param key 参数键
     * @return dictDatas 字典数据列表
     */
    public static List<SysDictData> getDictCache(String key)
    {
        Object cacheObj = SpringUtils.getBean(RedisService.class).getCacheObject(getCacheKey(key));
        if (ObjectUtils.isNotEmpty(cacheObj))
        {
            return (List<SysDictData>) (cacheObj);
        }
        return Collections.emptyList();
    }

    /** 获取字典标签名 */
    public static String getDictDataLabel(String key, String value, String defaultValue) {
        List<SysDictData> dictDataList = getDictCache(key);
        if(dictDataList == null) {
            return defaultValue;
        }
        List<SysDictData>  newDictDataList = dictDataList.stream().filter(i -> i.getDictValue().equals(value)).collect(Collectors.toList());
        if(newDictDataList != null && newDictDataList.size() == 1) {
            return newDictDataList.get(0).getDictLabel();
        }else {
            return defaultValue;
        }
    }

    /**
     * 清空字典缓存
     */
    public static void clearDictCache()
    {
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        Collection<String> keys = redisService.keys(SystemRedisKeys.SYS_DICT_KEY.key() + "*");
        keys.forEach(key -> redisService.deleteObject(key));
    }

    /**
     * 设置cache key
     * 
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getCacheKey(String configKey)
    {
        return SystemRedisKeys.SYS_DICT_KEY.key() + configKey;
    }
}
